//Made a new auto spawner, are you happy now Infinity
print("Lud Life Tree auto spawner activating!")

LifeTrees = {}
local LT = LifeTrees
LT.HabitablePlanets = {}
LT.InHabitablePlanets = {}
LT.LocalTrees = {}
LT.Trees = {}
LT.Rocks = {}
LT.Total = 0
LT.Tables = 1


function BuildTable()
	for k,v in pairs(environments) do 
		if v.air.o2per > 10 then 
			LT.HabitablePlanets[k] = v
			print("Planet added to habitable list")
		else
			LT.InHabitablePlanets[k] = v
			print("Planet added to inhabitable list")
		end 
	end
end

function GetTrees(pos)
	for index, tree in pairs(ents.FindInSphere(pos, 8000)) do
		if tree:GetClass()=="lud_life_tree" then
//			print("Added Tree to table!")
			LT.LocalTrees[index] = tree
		end
	end
end


function SpawnTree()
	if LT.Tables==1 then
		BuildTable()
		LT.Tables=0
	end
	local TreePlanets = table.Count(LT.HabitablePlanets)
	for i=1, TreePlanets do
		local nom = LT.HabitablePlanets[i]
		for i=1,10 do
			local rspot = math.random(350,nom.radius)
			local pos = math.RandomCirclePoint(nom:GetPos(), rspot - 300, nil)
			GetTrees(pos)
			local Nearby = table.Count(LT.LocalTrees)
			print("Got nearby trees. "..Nearby)
			if Nearby > 10 then
				return false
			end
			local ent = ents.Create("lud_life_tree")

			ent:Spawn()
			ent:SetPos(pos)--Send the tree to the correct spot!
			print("Made a tree!")
		end
	end
end


function math.RandomCirclePoint(vec, rad, p)
	print("Creating circle offset")
	local cur = Vector(rad, 0, 0)
	cur:Rotate(Angle(p or 0,math.random(0,360),0))
	return cur + vec --offset to change the origin to the supplied vector
end

function Prepare()
	print("Preparing to make stuff")
	LT.Total = table.Count(ents.FindByClass("lud_life_tree"))
	local Random = math.random(1,4)
	print("Found this many trees "..LT.Total.." And Random is "..Random)
	if (Random == 1 and LT.Total < 80) then
		print("Sending Spawn function a go!")
		SpawnTree()
	end
end

if(SERVER)then
//	timer.Create("Derp", 5, 0, Prepare)
	concommand.Add("force_trees", Prepare) 
	Prepare()
end

